package com.leisurexi.aop.overview;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * JDK 动态代理示例
 *
 * @author: leisurexi
 * @date: 2021-05-20 14:59
 */
public class JdkDynamicProxyDemo {

    public static void main(String[] args) {
        ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
        EchoService target = new DefaultEchoService();
        Object proxy = Proxy.newProxyInstance(classLoader, new Class[]{EchoService.class}, new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                if (method.getDeclaringClass().isAssignableFrom(EchoService.class)) {
                    long startTime = System.currentTimeMillis();
                    Object result = method.invoke(target, args);
                    long costTime = System.currentTimeMillis() - startTime;
                    System.out.println("echo 方法执行时间: " + costTime + " ms.");
                    return result;
                }
                return null;
            }
        });
        EchoService proxyEchoService = (EchoService) proxy;
        proxyEchoService.echo("hi, leisurexi");
        proxyEchoService.echo("hi, leisurexi");
    }

}
